package com.jtcoding.distributedlock.commons;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

/**
 * @Author jason.tang
 * @Date 2020/01/23 11:16
 * @Desc Redis 分布式锁
 */
@Slf4j
@Component()
public class RedisLock {

    @Autowired
    private RedisHelper redisHelper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Value("${redis.seckill.timeout}")
    private Integer seckillTimeout;

    /**
     * 加锁
     * @param key id
     * @param value current time +  lock timeout
     * @return
     */
    public boolean lock(String key, String value) {
        boolean isLock = redisHelper.setIfAbsent(key, value, seckillTimeout);
        if (isLock) {
            return true;
        }
        return false;
    }

    /**
     * 解锁
     * @param key
     * @param value
     */
    public void unlock(String key, String value) {
        try {
            String orgValue = stringRedisTemplate.opsForValue().get(key);
            if (StringUtils.isNotBlank(orgValue) && orgValue.equals(value)) {
                stringRedisTemplate.opsForValue().getOperations().delete(key);
            }
        } catch (Exception e) {
            log.error("Unlock Exception: Key: {}, Value: {}", key, value, e);
        }
    }
}
